var pagecontext_ctx = $("#pagecontext_ctx").val();
$(function(){
	  //左侧导航栏切换	
	setMenu(pagecontext_ctx+"/user_manage/role_manage");
	//新增角色
	 $("#roleAdd").on("click",function(){
		 //新增改标题且表单全部置空
		 $("#save_resert").trigger("click");
		 $("#Add").modal("show");
	 })
	 
	    //添加角色
	     $("#sava_role").on("click", function() {
	    	 var roleName = $("#save_roleName").val();
	    	 if(roleName == null || roleName == '') {
	    		 layer.msg("角色名称不能为空!");
	    		 return;
	    	 }
	    	 
	    	 var remark = $("#save_remark").val();
	    	 
	    	  $.ajax({
                type:"post",
                url:pagecontext_ctx+"/role/insertRoles",
                data:{"roleName":roleName, "remark":remark},
                dataType:"json",
                success:function(result){
                       if(result.success){
                             layer.msg(result.msg);
                             location = pagecontext_ctx+"/user_manage/role_manage";
                      }else{
                    	  alert(result.msg);
                      }
                }, error:function(XMLHttpRequest, textStatus, errorThrown) {
			  if(XMLHttpRequest.status == 403) {
			      alert("没有权限!");
			}
			}  //error end
			         }); //-------ajax end-------
	    	 
	     });
	
	 //刚进入页面
	 rolepage(null);
	//回车查询
	    document.onkeydown = function (e) {//按键信息对象以函数参数的形式传递进来了，就是那个e  
	        var code = e.charCode || e.keyCode;    
	        if (code == 13) {  
	            //此处编写用户敲回车后的代码  
	        	rolepage(null);
	        }  
	    }
	 
	 //分页查询
	 $("#roleSearch").on("click",function(){
		 rolepage(null);
	 })
	 
	 function rolepage(page){
		 var rolename=$("#searchForm input[name='rolename']").val();
		 //console.log(rolename)
		//ajax发送之前显示loading
		 $("#loading").show();
		 $.ajax({
			 type:"post",
			 url:pagecontext_ctx+"/role/findRolesListPage",
			 data:{"page":page, "roleName":rolename},
			 dataType:"json",
			 success:function(result){
				// Ajax请求结束的时候触发
		            setTimeout(function(){
		                 $('#loading').hide();
		                },500);
	               if(result.page.list.length==0){
	            	   $("#tableList").html("");
	                      $("#pageUI").html("");
	                	   layer.msg("暂无数据！");
	                	   return false;
	               }
				 // console.log(result)
	               
	              var content="";
	              $.each(result.page.list,function(i,item){
	            	  var id = "";
			 			if(item.id != "" && item.id != null) {
			 				guid = item.guid;
			 			}
			 			content+="<tr class='parent' data-guid='"+id+"' >";
			 			
			 			//角色名称
			 			var rolename = "";
			 			if(item.roleName!=null && item.roleName!='') {
			 				roleName=item.roleName;
			 			}
			 			content+="<td>"+roleName+"</td>";
			 			
			 			//角色描述
			 			var remark = "";
			 			if(item.remark != "" && item.remark != null) {
			 				remark = item.remark;
			 			}
			 			content+="<td>"+remark+"</td>";
			 			
			 			content+="<td>";
			 			content+="<div class='btn-group'>"; 
			 		    content+="<button class='btn btn-xs btn-info edit_role' data="+item.id+"><i class='ace-icon fa fa-pencil bigger-120'></i>修改</button>"; 
						content+="<button class='btn btn-xs btn-danger delete_role' data="+item.id+"><i class='ace-icon fa fa-trash-o bigger-120'></i>删除</button>";
						content+="<button class='btn btn-xs btn-warning allot_authority' data="+item.id+"><i class='ace-icon fa fa-key bigger-120'></i>分配权限</button>";
						content+="</div>";
						content+="</td>";
			 			content+="</tr>";
	              });
	              
	              //将内容渲染在body中
	              $("#tableList").html(content);
	              
	              
	            //修改事件
	              $(".edit_role").on("click",function(){
	            	 var id = $(this).attr("data");
	            	   //var dataGuid=$(this).parents(".parent").attr("data-guid");
	            	   $.ajax({
	            		     type:"get",
			 				 url:pagecontext_ctx+"/role/findRoleById",
			 				 data:{"id":id},
			 				 success:function(result){
			 					 console.log(result);
			 					//获取回写信息
			 					//把获取的version和guid添加到内容中
				 				 $("#update_resert").trigger("click");
				 				 $("#update_id").val(result.role.id);
			 					 $("#update_remark").val(result.role.remark||"");
			 					 $("#update_roleName").val(result.role.roleName);
			 				     //显示模态框
			 					 $("#update").modal("show");
			 				 }
	            	   })
	              }) //修改结束
	              
	              //修改角色
	              $("#update_role").on("click", function() {
	            	  var id = $("#update_id").val();
	 				  var remark = $("#update_remark").val();
	 				  var roleName = $("#update_roleName").val();
	 				  var dataJson = {"id":id, "remark":remark, "roleName":roleName};
	            	 
	 				  if(roleName == null || roleName == '') {
	            		  alert("角色名称不能为空!");
	            		  return;
	            	  }
	            	  
	 			     $.ajax({
                       type:"post",
                       url:pagecontext_ctx+"/role/updateRoles",
                       data:dataJson,
                       dataType:"json",
                       success:function(result){
                              if(result.success){
                                    alert(result.msg);
                                    location = pagecontext_ctx+"/user_manage/role_manage";
                             }else{
                                    alert(result.msg);
                             }
                       }, error:function(XMLHttpRequest, textStatus, errorThrown) {
         if(XMLHttpRequest.status == 403) {
             alert("没有权限!");
      }
  }  //error end
                }); //-------ajax end-------

	            	  
	              });
	              
	              
	              
	              //删除功能
		 		$(".delete_role").on("click",function(){
		 			var id = $(this).attr("data");
		 			$.ajax({
			 				type:"post",
			 				url:pagecontext_ctx+"/role/deleteRoles",
			 				data:{"roleId":id},
			 				dataType:"json",
			 				success:function(result){
			 					console.log(result)
			 					if(result.success){
			 						alert(result.msg);
			 						location = pagecontext_ctx+"/user_manage/role_manage";
			 					}else{
			 						alert(result.msg);
			 					}
			 				}, error:function(XMLHttpRequest, textStatus, errorThrown) {
                                if(XMLHttpRequest.status == 403) {
                                    alert("没有权限!");
                             }
                       }  //error end 

			 			})	
		 			
		 		}); //删除结束
	              
	              
	            //初始化权限树 ------------begin
	            $(".allot_authority").on("click", function() {
	            	$("input[name='allot_authority']").each(function() {
	            		$(this).attr("checked",false);
	            	});
	            	$("#demo").html("");
	            	var roleId = $(this).attr("data");
	            	$("#allot_authority_model_roleId").val(roleId);
	            	var url = pagecontext_ctx+"/authority/findAuthorityList";
	            	$.ajax({
                        type:"get",
                        url:url,
                        dataType:"json",
                        data: {
                            "roleId": roleId
                       },
                        success:function(result){
                         	//初始化权限树
        	            	layui.use('tree', function() {
        	    				var tree = layui.tree({
        	    					elem: '#demo', //指定元素，生成的树放到哪个元素上
        	    					check: 'checkbox', //勾选风格
        	    					skin: 'as', //设定皮肤
        	    					drag: true,//点击每一项时是否生成提示信息
        	    					checkboxName: 'allot_authority',//复选框的name属性值
        	    					checkboxStyle: "",//设置复选框的样式，必须为字符串，css样式怎么写就怎么写
        	    					nodes: result.authorityList
        	    				});
        	    			});
                        },
                        error:function(XMLHttpRequest, textStatus, errorThrown) {
                              if(XMLHttpRequest.status == 403) {
                                     alert("没有权限!");
                              }
                        }  //error end 
                       
                 }); //ajax 结束

	            	
	            	$("#allot_authority_model").modal("show");
	            	
	            });//初始化权限树  ------------- end
	            
	            
	            //----分配权限 begin------
	            $("#save_allot_authority").on("click", function() {
	            	var $allAuthority = $("input[name='allot_authority']");
	            	var authorityArray = [];
	            	if($allAuthority.length > 0) {
	            		$allAuthority.each(function() {
	            			if($(this).is(":checked")) {
	            				authorityArray.push($(this).attr("value"));
	            			}
	            		});
	            	}
	            	
	            	var authorityStr = authorityArray.join(",");
	            	var dataform = {"roleId":$("#allot_authority_model_roleId").val(), "authorityStr":authorityStr};
	            	$.ajax({
                        type:"post",
                        url:pagecontext_ctx+"/role/updateRoleToAllAuthority",
                        dataType:"json",
                        data:dataform,
                        success:function(result){
                             if(result.success){
                                   alert(result.msg);
                                   location = pagecontext_ctx+"/user_manage/role_manage";
                             }else{
                            	 alert(result.msg);
                             }
                        },
                        error:function(XMLHttpRequest, textStatus, errorThrown) {
                              if(XMLHttpRequest.status == 403) {
                                     alert("没有权限!");
                              }
                        }  //error end 
                       
                 }); //ajax 结束
	            	
	            });
	            //-----分配权限 end---------
	            
		 			var element = $("#pageUI");	
					var options = {
									 bootstrapMajorVersion:3,
									 currentPage:result.page.currentPage,
									 numberOfPages:3,
									 totalPages:result.page.totalPage,
								     itemTexts: function(type, page, current) { //修改显示文字
						                switch (type) {
						                case "first":
						                    return "第一页";
						                case "prev":
						                    return "上一页";
						                case "next":
						                    return "下一页";
						                case "last":
						                    return "最后一页";
						                case "page":
						                    return page;
						                }
								     },
									 onPageChanged:function(event, originalEvent, currentPage){
										rolepage(currentPage);
									 }
					               }; //----options
		           element.bootstrapPaginator(options);
			   },  error:function(XMLHttpRequest, textStatus, errorThrown) {
                   $("#loading").hide();
				   if(XMLHttpRequest.status == 403) {
                       alert("没有权限!");
                }
          }  //error end 

			 })
	 }
	 

});
